<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>手写promise</title>
</head>
<body>
    <script>
        /*189000526-谭静*/
        //1：
        function Promise(executor){
            executor(resolve,reject);
            function resolve(){}
            function reject(){}
        }
        //2：
        function Promise(executor){
            let _this = this;
            _this.$$status = 'pending';//设置最初的状态为正在进行中
            executor(resolve.bind(this),reject.bind(this));
            function resolve(){
                if(_this.$$status === 'pending'){
                    _this.$$status = 'full';
                }
            }
            function reject(){
                if(_this.$$status === 'pending'){
                    _this.$$status = 'fail';
                } 
            }
        }

        //3:
        Promise.prototype.then = function(full,fail){
            this.successCallback = full;
            this.failCallBack = fail;
        };

        //4:
        function Promise(executor){
            let _this = this;
            _this.$$status = 'pending';
            _this.failCallBack = undefined;
            _this.successCallback = undefined;
            _this.error = undefined;
            executor(resolve.bind(_this),reject.bind(_this));

            function resolve(params){
                if(_this.$$status === 'pending'){
                    _this.$$status = 'success';
                    _this.successCallback(params);
                }
            }
            function reject(params){
                if(_this.$$status ==  'pending'){
                    _this.$$status = 'fail';
                    _this.failCallBack(params);
                }
            }
        }

        //5:
        new Promise(function(res,rej){
            setTimeout(() => res('成功'), 0);
        }).then(result => console.log(result));

        //6:思考then函数的链式调用该如何实现
        /*then()方法的作用是Promise实例添加解决（fulfillment）和拒绝（rejection）状态的回调函数。
        then()方法会返回一个新的Promise实例，所以then()方法后面可以继续跟另一个then()方法进行链式调用,
        但是前一个then()方法中的回调函数中又可能返回一个Promise实例，这时候后面一个then()方法中
        的回调函数会等前一个Promise实例的状态发生变化才会调用*/
    </script>
</body>
</html>